from datetime import datetime
from storage_manager import load_all_messages_from_file, delete_message_by_id, update_message_by_id, add_comment_to_message, like_message

# 假设管理员密码为 "admin123"
ADMIN_PASSWORD = "admin123"

def admin_login():
    password = input("请输入管理员密码: ").strip()
    return password == ADMIN_PASSWORD

def admin_interface():
    if not admin_login():
        print("密码错误，无法进入管理界面!")
        return

    all_messages = load_all_messages_from_file()
    count = 5
    # 按时间倒序排序
    sorted_messages = sorted(all_messages, key=lambda x: x['timestamp'], reverse=True)

    # 分页逻辑
    total_pages = (len(sorted_messages) + count - 1) // count
    current_page = 1

    while True:
        start_idx = (current_page - 1) * count
        end_idx = min(start_idx + count, len(sorted_messages))
        page_messages = sorted_messages[start_idx:end_idx]

        if not page_messages:
            print("没有更多消息了。")
            break

        print(f"\n第 {current_page}/{total_pages} 页")
        for msg in page_messages:
            print(format_message_for_display(msg))

        if total_pages > 1:
            action = input("输入 ['N' 下一页]，['P' 上一页]，['D' 删除消息]，['U' 更新消息]，其他键返回: ").strip().lower()
            if action == 'n' and current_page < total_pages:
                current_page += 1
            elif action == 'p' and current_page > 1:
                current_page -= 1
            elif action == 'd':
                message_id = input("请输入要删除的消息 ID: ").strip()
                message_exists = any(msg["message_id"] == message_id for msg in all_messages)
                if message_exists:
                    delete_message_by_id(message_id)
                    print("消息已删除。")
                else:
                    print("未找到该消息，无法删除。")
                all_messages = load_all_messages_from_file()
                sorted_messages = sorted(all_messages, key=lambda x: x['timestamp'], reverse=True)
                total_pages = (len(sorted_messages) + count - 1) // count
            elif action == 'u':
                message_id = input("请输入要更新的消息 ID: ").strip()
                message_exists = any(msg["message_id"] == message_id for msg in all_messages)
                if message_exists:
                    new_content = input("请输入新的消息内容: ").strip()
                    update_message_by_id(message_id, new_content)
                    print("消息已更新。")
                else:
                    print("未找到该消息，无法更新。")
                all_messages = load_all_messages_from_file()
                sorted_messages = sorted(all_messages, key=lambda x: x['timestamp'], reverse=True)
                total_pages = (len(sorted_messages) + count - 1) // count
            else:
                break
        else:
            action = input("输入 ['D' 删除消息]，['U' 更新消息]，其他键返回: ").strip().lower()
            if action == 'd':
                message_id = input("请输入要删除的消息 ID: ").strip()
                message_exists = any(msg["message_id"] == message_id for msg in all_messages)
                if message_exists:
                    delete_message_by_id(message_id)
                    print("消息已删除。")
                else:
                    print("未找到该消息，无法删除。")
                all_messages = load_all_messages_from_file()
                sorted_messages = sorted(all_messages, key=lambda x: x['timestamp'], reverse=True)
                total_pages = (len(sorted_messages) + count - 1) // count
            elif action == 'u':
                message_id = input("请输入要更新的消息 ID: ").strip()
                message_exists = any(msg["message_id"] == message_id for msg in all_messages)
                if message_exists:
                    new_content = input("请输入新的消息内容: ").strip()
                    update_message_by_id(message_id, new_content)
                    print("消息已更新。")
                else:
                    print("未找到该消息，无法更新。")
                all_messages = load_all_messages_from_file()
                sorted_messages = sorted(all_messages, key=lambda x: x['timestamp'], reverse=True)
                total_pages = (len(sorted_messages) + count - 1) // count
            else:
                break

def create_message_object():
    """创建新消息对象"""
    print("请输入消息内容 [输入单独的 'EOF' 结束]：")
    lines = []
    while True:
        line = input()
        if line.strip() == "EOF":
            break
        lines.append(line)

    content = "\n".join(lines)
    if not content.strip():
        print("消息内容不能为空！")
        return None

    # 获取可选的发布口令
    token = input("请输入发布口令 [可选，直接回车跳过]：").strip()

    # 生成唯一消息ID
    all_messages = load_all_messages_from_file()
    if all_messages:
        max_id = max(int(msg["message_id"]) for msg in all_messages)
        message_id = str(max_id + 1)
    else:
        message_id = "1"

    # 获取当前时间戳
    timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")

    return {
        "message_id": message_id,
        "timestamp": timestamp,
        "content": content,
        "user_token": token,
        "comments": [],
        "likes": 0
    }

def post_new_message_interaction():
    """处理发布新消息的交互"""
    message = create_message_object()
    if not message:
        return None

    print("\n即将发布的消息：")
    print(format_message_for_display(message))

    confirm = input("确认发布？[y/n]: ").strip().lower()
    return message if confirm == 'y' else None

def format_message_for_display(message_dict):
    """格式化消息以便在终端显示"""
    result = (
        f"[消息ID: {message_dict['message_id']}] (发布于: {message_dict['timestamp']})\n"
        f"内容：\n"
        f"{message_dict['content']}\n"
    )
    if "likes" in message_dict:
        result += f"点赞数: {message_dict['likes']}\n"
    if "comments" in message_dict:
        result += "评论:\n"
        for comment in message_dict["comments"]:
            result += f" - {comment}\n"
    result += "-" * 40
    return result

def view_latest_messages_interaction(all_messages, count=5):  # 修改默认显示数量为5
    """查看最新消息的交互"""
    if not all_messages:
        print("暂无消息。")
        return

    # 按时间倒序排序
    sorted_messages = sorted(all_messages, key=lambda x: x['timestamp'], reverse=True)

    # 分页逻辑
    total_pages = (len(sorted_messages) + count - 1) // count
    current_page = 1

    while True:
        start_idx = (current_page - 1) * count
        end_idx = min(start_idx + count, len(sorted_messages))
        page_messages = sorted_messages[start_idx:end_idx]

        if not page_messages:
            print("没有更多消息了。")
            break

        print(f"\n第 {current_page}/{total_pages} 页")
        for msg in page_messages:
            print(format_message_for_display(msg))

        if total_pages > 1:
            action = input("输入 ['N' 下一页]，['P' 上一页]，['C' 评论]，['L' 点赞]，其他键返回: ").strip().lower()
            if action == 'n' and current_page < total_pages:
                current_page += 1
            elif action == 'p' and current_page > 1:
                current_page -= 1
            elif action == 'c':
                message_id = input("请输入要评论的消息 ID: ").strip()
                comment = input("请输入评论内容: ").strip()
                if not comment:
                    print("评论内容不能为空！")
                else:
                    found = False
                    for msg in all_messages:
                        if msg["message_id"] == message_id:
                            add_comment_to_message(message_id, comment)
                            found = True
                            print("评论已添加。")
                            all_messages = load_all_messages_from_file()
                            sorted_messages = sorted(all_messages, key=lambda x: x['timestamp'], reverse=True)
                            break
                    if not found:
                        print("未找到该消息，请检查消息 ID。")
            elif action == 'l':
                message_id = input("请输入要点赞的消息 ID: ").strip()
                found = False
                for msg in all_messages:
                    if msg["message_id"] == message_id:
                        like_message(message_id)
                        found = True
                        print("已点赞。")
                        all_messages = load_all_messages_from_file()
                        sorted_messages = sorted(all_messages, key=lambda x: x['timestamp'], reverse=True)
                        break
                if not found:
                    print("未找到该消息，请检查消息 ID。")
            else:
                break
        else:
            action = input("输入 ['C' 评论]，['L' 点赞]，其他键返回: ").strip().lower()
            if action == 'c':
                message_id = input("请输入要评论的消息 ID: ").strip()
                comment = input("请输入评论内容: ").strip()
                if not comment:
                    print("评论内容不能为空！")
                else:
                    found = False
                    for msg in all_messages:
                        if msg["message_id"] == message_id:
                            add_comment_to_message(message_id, comment)
                            found = True
                            print("评论已添加。")
                            all_messages = load_all_messages_from_file()
                            sorted_messages = sorted(all_messages, key=lambda x: x['timestamp'], reverse=True)
                            break
                    if not found:
                        print("未找到该消息，请检查消息 ID。")
            elif action == 'l':
                message_id = input("请输入要点赞的消息 ID: ").strip()
                found = False
                for msg in all_messages:
                    if msg["message_id"] == message_id:
                        like_message(message_id)
                        found = True
                        print("已点赞。")
                        all_messages = load_all_messages_from_file()
                        sorted_messages = sorted(all_messages, key=lambda x: x['timestamp'], reverse=True)
                        break
                if not found:
                    print("未找到该消息，请检查消息 ID。")
            else:
                break

def search_messages_by_keyword(all_messages, keyword):
    """按关键词搜索消息"""
    keyword = keyword.lower()
    return [msg for msg in all_messages if keyword in msg["content"].lower()]

def search_messages_interaction(all_messages):
    """搜索消息的交互"""
    keyword = input("请输入搜索关键词: ").strip()
    if not keyword:
        print("搜索关键词不能为空！")
        return

    results = search_messages_by_keyword(all_messages, keyword)
    # 按时间倒序排序
    sorted_results = sorted(results, key=lambda x: x['timestamp'], reverse=True)

    count = 5
    # 分页逻辑
    total_pages = (len(sorted_results) + count - 1) // count
    current_page = 1

    while True:
        start_idx = (current_page - 1) * count
        end_idx = min(start_idx + count, len(sorted_results))
        page_messages = sorted_results[start_idx:end_idx]

        if not page_messages:
            print("没有更多消息了。")
            break

        print(f"\n第 {current_page}/{total_pages} 页，找到 {len(results)} 条相关消息：")
        for msg in page_messages:
            print(format_message_for_display(msg))

        if total_pages > 1:
            action = input("输入 ['N' 下一页]，['P' 上一页]，['C' 评论]，['L' 点赞]，其他键返回: ").strip().lower()
            if action == 'n' and current_page < total_pages:
                current_page += 1
            elif action == 'p' and current_page > 1:
                current_page -= 1
            elif action == 'c':
                message_id = input("请输入要评论的消息 ID: ").strip()
                comment = input("请输入评论内容: ").strip()
                if not comment:
                    print("评论内容不能为空！")
                else:
                    found = False
                    for msg in all_messages:
                        if msg["message_id"] == message_id:
                            add_comment_to_message(message_id, comment)
                            found = True
                            print("评论已添加。")
                            all_messages = load_all_messages_from_file()
                            results = search_messages_by_keyword(all_messages, keyword)
                            sorted_results = sorted(results, key=lambda x: x['timestamp'], reverse=True)
                            total_pages = (len(sorted_results) + count - 1) // count
                            break
                    if not found:
                        print("未找到该消息，请检查消息 ID。")
            elif action == 'l':
                message_id = input("请输入要点赞的消息 ID: ").strip()
                found = False
                for msg in all_messages:
                    if msg["message_id"] == message_id:
                        like_message(message_id)
                        found = True
                        print("已点赞。")
                        all_messages = load_all_messages_from_file()
                        results = search_messages_by_keyword(all_messages, keyword)
                        sorted_results = sorted(results, key=lambda x: x['timestamp'], reverse=True)
                        total_pages = (len(sorted_results) + count - 1) // count
                        break
                if not found:
                    print("未找到该消息，请检查消息 ID。")
            else:
                break
        else:
            action = input("输入 ['C' 评论]，['L' 点赞]，其他键返回: ").strip().lower()
            if action == 'c':
                message_id = input("请输入要评论的消息 ID: ").strip()
                comment = input("请输入评论内容: ").strip()
                if not comment:
                    print("评论内容不能为空！")
                else:
                    found = False
                    for msg in all_messages:
                        if msg["message_id"] == message_id:
                            add_comment_to_message(message_id, comment)
                            found = True
                            print("评论已添加。")
                            all_messages = load_all_messages_from_file()
                            results = search_messages_by_keyword(all_messages, keyword)
                            sorted_results = sorted(results, key=lambda x: x['timestamp'], reverse=True)
                            total_pages = (len(sorted_results) + count - 1) // count
                            break
                    if not found:
                        print("未找到该消息，请检查消息 ID。")
            elif action == 'l':
                message_id = input("请输入要点赞的消息 ID: ").strip()
                found = False
                for msg in all_messages:
                    if msg["message_id"] == message_id:
                        like_message(message_id)
                        found = True
                        print("已点赞。")
                        all_messages = load_all_messages_from_file()
                        results = search_messages_by_keyword(all_messages, keyword)
                        sorted_results = sorted(results, key=lambda x: x['timestamp'], reverse=True)
                        total_pages = (len(sorted_results) + count - 1) // count
                        break
                if not found:
                    print("未找到该消息，请检查消息 ID。")
            else:
                break

def filter_messages_by_token(all_messages, token):
    """按发布口令筛选消息"""
    return [msg for msg in all_messages if msg["user_token"] == token]

def view_my_posts_interaction(all_messages):
    """查看我的发布历史的交互"""
    token = input("请输入您的发布口令: ").strip()
    if not token:
        print("发布口令不能为空！")
        return

    my_posts = filter_messages_by_token(all_messages, token)

    if my_posts:
        # 按时间倒序排序
        sorted_my_posts = sorted(my_posts, key=lambda x: x['timestamp'], reverse=True)

        count = 5
        # 分页逻辑
        total_pages = (len(sorted_my_posts) + count - 1) // count
        current_page = 1

        while True:
            start_idx = (current_page - 1) * count
            end_idx = min(start_idx + count, len(sorted_my_posts))
            page_messages = sorted_my_posts[start_idx:end_idx]

            if not page_messages:
                print("没有更多消息了。")
                break

            print(f"\n第 {current_page}/{total_pages} 页，您共有 {len(sorted_my_posts)} 条发布：")
            for msg in page_messages:
                print(format_message_for_display(msg))

            if total_pages > 1:
                action = input("输入 ['N' 下一页]，['P' 上一页]，其他键返回: ").strip().lower()
                if action == 'n' and current_page < total_pages:
                    current_page += 1
                elif action == 'p' and current_page > 1:
                    current_page -= 1
                else:
                    break
            else:
                action = input("其他键返回: ").strip()
                break
    else:
        print("未找到使用该口令发布的消息。")